﻿using Fizzler.Systems.HtmlAgilityPack;
using HtmlAgilityPack;
using Yahoo.Yui.Compressor;

namespace HtmlDeploy
{
    public class Deploy
    {
        private readonly string path;
        private readonly string templatePath;

        public Deploy(string path, string templatePath)
        {
            this.path = path;
            this.templatePath = templatePath;
        }

        public void Process()
        {
            var jsRaw = new Script(path).Process();
            var cssRaw = new Css(path).Process();
            var jQueryTemplateRaw = new JqueryTemplate(templatePath).Process();

            cssRaw = CssCompressor.Compress(cssRaw);
            jsRaw = JavaScriptCompressor.Compress(jsRaw);

            var html = new HtmlDocument();
            html.Load(path);

            var head = html.DocumentNode.QuerySelector("head");

            var script = html.CreateElement("script");
            script.InnerHtml = jsRaw;
            script.SetAttributeValue("type", "text/javascript");

            var css = html.CreateElement("style");
            css.InnerHtml = cssRaw;
            css.SetAttributeValue("type", "text/css");

            var removes = html.DocumentNode.QuerySelectorAll("link, style, script");

            foreach (var remove in removes)
            {
                remove.ParentNode.RemoveChild(remove);
            }

            head.AppendChild(script);
            head.AppendChild(css);

            var body = html.DocumentNode.QuerySelector("body");

            var templateHtml = new HtmlDocument();
            templateHtml.LoadHtml(jQueryTemplateRaw);

            var templates = templateHtml.DocumentNode.QuerySelectorAll("script");

            foreach (var template in templates)
                body.AppendChild(template);

            html.Save(path + ".out.html");
        }
    }
}
